import { Router } from 'express'
import { body, query } from 'express-validator'
import { asyncHandler } from '../middleware/errorHandler'
import { handleValidationErrors, validatePagination } from '../middleware/validation'
import { authenticate, AuthRequest } from '../middleware/auth'
import { FamilyService } from '../services/familyService'

const router = Router()
const familyService = new FamilyService()

// All routes require authentication
router.use(authenticate)

// Get family trees
router.get('/trees', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { page, limit } = req.query as any
  const trees = await familyService.getFamilyTrees(req.user!.id, { page, limit })
  
  res.json({
    success: true,
    data: trees,
  })
}))

// Create family tree
router.post('/trees', [
  body('name').notEmpty().withMessage('Tree name is required'),
  body('rootMemberId').isInt().withMessage('Root member ID must be an integer'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const treeData = req.body
  const tree = await familyService.createFamilyTree({ ...treeData, createdBy: req.user!.id })
  
  res.status(201).json({
    success: true,
    data: tree,
  })
}))

// Get family tree by ID
router.get('/trees/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const tree = await familyService.getFamilyTreeById(parseInt(id))
  
  if (!tree) {
    throw new Error('Family tree not found')
  }
  
  res.json({
    success: true,
    data: tree,
  })
}))

// Update family tree
router.put('/trees/:id', [
  body('name').optional().notEmpty().withMessage('Tree name cannot be empty'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const updateData = req.body
  
  const tree = await familyService.updateFamilyTree(parseInt(id), updateData)
  
  res.json({
    success: true,
    data: tree,
  })
}))

// Delete family tree
router.delete('/trees/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  await familyService.deleteFamilyTree(parseInt(id))
  
  res.json({
    success: true,
    message: 'Family tree deleted successfully',
  })
}))

// Get family members
router.get('/members', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { page, limit, search } = req.query as any
  const members = await familyService.getFamilyMembers({ page, limit, search })
  
  res.json({
    success: true,
    data: members,
  })
}))

// Create family member
router.post('/members', [
  body('name').notEmpty().withMessage('Member name is required'),
  body('gender').isIn(['MALE', 'FEMALE']).withMessage('Gender must be MALE or FEMALE'),
  body('generation').isInt().withMessage('Generation must be an integer'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const memberData = req.body
  const member = await familyService.createFamilyMember(memberData)
  
  res.status(201).json({
    success: true,
    data: member,
  })
}))

// Get family member by ID
router.get('/members/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const member = await familyService.getFamilyMemberById(parseInt(id))
  
  if (!member) {
    throw new Error('Family member not found')
  }
  
  res.json({
    success: true,
    data: member,
  })
}))

// Update family member
router.put('/members/:id', [
  body('name').optional().notEmpty().withMessage('Member name cannot be empty'),
  body('gender').optional().isIn(['MALE', 'FEMALE']).withMessage('Gender must be MALE or FEMALE'),
  body('generation').optional().isInt().withMessage('Generation must be an integer'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const updateData = req.body
  
  const member = await familyService.updateFamilyMember(parseInt(id), updateData)
  
  res.json({
    success: true,
    data: member,
  })
}))

// Delete family member
router.delete('/members/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  await familyService.deleteFamilyMember(parseInt(id))
  
  res.json({
    success: true,
    message: 'Family member deleted successfully',
  })
}))

// Get family tree structure (hierarchical)
router.get('/trees/:id/structure', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const structure = await familyService.getFamilyTreeStructure(parseInt(id))
  
  res.json({
    success: true,
    data: structure,
  })
}))

export { router as familyRouter }